package com.log;

import java.util.Date;

import com.log.Event.LogEvent;
import com.log.listener.LogListener;

public class LogMonitor {
    private StringBuffer logs;
    private LogListener listener = null;
    
    public LogMonitor() {
		logs = new StringBuffer();
		listener = new LogListener() {
			@Override
			public void EventActivated(LogEvent me) {
			}
		};
	}
    
    public LogMonitor(StringBuffer sb) {
		logs = sb;
		listener = new LogListener() {
			@Override
			public void EventActivated(LogEvent me) {
			}
		};
	}
    
    public LogMonitor(LogListener listener) {
    	logs = new StringBuffer();
    	this.listener = listener;
    }
    
    /**
     * 获取日志信息
     * @return
     */
    public String toString() {
        return logs == null ? "" : logs.toString();
    }
    
    /**
     * 复制对象
     */
    public LogMonitor clone() {
    	LogMonitor newLog = new LogMonitor();
    	newLog.setLogChangedListener(listener);
    	return newLog;
    }
    
    /**
     * 新增日志信息
     * @param log
     */
    public void appendFormatLog(String log) {
        if(log == null || "".equals(log)) {
            logs.append("\r\n");
        } else {
        	log = String.format("%s    %s\r\n", new Date().toString(), log);
            logs.append(log);
        }
        activateLogChangedEvent();
    }
    
    /**
     * 新增日志信息
     * @param log
     */
    public void append(String log) {
    	System.out.println(log);
        if(log == null || "".equals(log)) {
            logs.append("\r\n");
        } else {
            logs.append(log + "\r\n");
        }
        activateLogChangedEvent();
    }
    
    /**
     * 清除日志信息
     */
    public void clearLogs() {
        logs = new StringBuffer();
        activateLogChangedEvent();
    }
    
    public boolean hasListener() {
    	return listener == null ? false : true;
    }
    
    public void setLogChangedListener(LogListener l) {
        listener = l;
    }
    
	public void activateLogChangedEvent() {
        LogEvent e = new LogEvent(LogMonitor.class);
        if (hasListener()) {
        	listener.EventActivated(e);
		}
    }
}